library(ggplot2)
library(dplyr)
library(readr)

# setwd

plot_data <- read_table("figures1_data.txt")

est_mod1 <- as.vector(plot_data[seq(1,13,2),2])
est_mod2 <- as.vector(plot_data[seq(1,13,2),3])
est_mod3 <- as.vector(plot_data[seq(1,13,2),4])

se_mod1 <- plot_data[seq(2,14,2),2]
se_mod2 <- plot_data[seq(2,14,2),3]
se_mod3 <- plot_data[seq(2,14,2),4]

plot_data <- data_frame(est = c(est_mod1$X2, est_mod2$X3, est_mod3$X4),
                        se  = c(se_mod1$X2,  se_mod2$X3,  se_mod3$X4),
                        lab = rep(c("\nAll survey respondents ", 
                                    "\nSurvey respondents without \nvalidated turnout ", 
                                    "\nSurvey respondents with \nvalidated turnout"), each = 7), 
                        pla = c(seq(1.2, 7.2, 1), seq(0.8, 6.8, 1), seq(1, 7, 1)  ))

plot_data <- 
  plot_data %>% 
  mutate(est = 100 * as.numeric(est),
         se  = 100 * as.numeric(se))

plot_data[c(1,8,15),1] <- plot_data[c(1,8,15),1]$est*10
plot_data[c(1,8,15),2] <- plot_data[c(1,8,15),2]$se *10


ggplot(data = na.omit(plot_data),
       aes(x = est,
           y = pla, 
           xmax = qnorm(0.975)*se + est,
           xmin = qnorm(0.025)*se + est)) + 
  geom_errorbarh(aes(color = lab), height = 0) + 
  geom_point(aes(color = lab), size = 3) + 
  theme_classic() + 
  xlab("Difference in turnout") + 
  ylab("") +
  scale_y_continuous(breaks = 1:7,
                     labels = c("Age (10 years)",
                                "High School",
                                "Vocational training",
                                "Short/mid-cycle",
                                "Long-cycle",
                                "Female",
                                "Non-native")) +
  scale_color_manual(values=c("black", "grey50", "grey75"),
                     guide_legend(title = "",
                                  title.position = "top")) + 
  geom_vline(xintercept = 0, lty = 2, alpha = 0.3)

ggsave(plot = last_plot(), filename = "figureS1.pdf", width = 8, height = 4, dpi = 300)


